package struts.action;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.bean.ActionForm;
import struts.bean.XmlBean;
import struts.com.ReflectUtil;

public class ActionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7127150859111716940L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
//		String username = request.getParameter("username");
//		String url = "";
//		if (username.equals("shi")) {
//			
//			url = "/view/success.jsp";
//		}
//		else
//		{
//			url = "/view/failture.jsp";
//		}
//		Map<String, XmlBean> configMap = StrutsConfig.strutsConfigXml();

		Map<String, XmlBean> configMap = (Map<String, XmlBean>)this.getServletContext().getAttribute("struts-config");
		// 得到请求头
		String path = request.getServletPath().split("\\.")[0];
		System.out.println(path);
		XmlBean xmlbean = configMap.get(path);
		
		String beanclass = xmlbean.getBeanClass();
		String actionclass = xmlbean.getActionClass();
		Map<String, String> forwards = xmlbean.getForwords();
		ActionForm af = null;
		ActionForm af1 = null;
		Action action = null;
		
		// -------------------add by shi 给当前javabean自动赋值-----------------------
		af1 = (ActionForm)ReflectUtil.invoke(beanclass, request);
		System.out.println(af1);
		// 通过反射得到bean和action的实例
		try
		{
//			Class<?> clazz = Class.forName(beanclass);
//			af = (ActionForm)clazz.newInstance();
//			
//			Field[] fs = clazz.getDeclaredFields();
//			for(Field f:fs) {
//				
//				f.setAccessible(true);
//				f.set(af, request.getParameter(f.getName()));
//				f.setAccessible(false);
//			}
			
			Class<?> clazz2 = Class.forName(actionclass);
			action = (Action)clazz2.newInstance();
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		String url = action.execute(request, response, af1, forwards);
		
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		this.doGet(request, response);
	}
	
}
